package com.jiang.service;

import com.jiang.Domain.Message;
import com.jiang.Domain.MessageType;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * @author Jiang
 * @version 1.0
 * @date 2023/11/29 11:05
 */
public class ClientConnectServerThread implements Runnable {
    private Socket socket;

    public ClientConnectServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("客户端线程，等待读取从服务器发送的消息");
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) objectInputStream.readObject();

                if (MessageType.MESSAGE_RET_ONLINE_FRIEND.equals(message.getMesType())) {
                    String[] onlineUsers = message.getContent().split(" ");
                    System.out.println("\n========当前在线用户列表==========");
                    for (int i = 0; i < onlineUsers.length; i++) {
                        System.out.println("用户：" + onlineUsers[i]);
                    }
                } else if (MessageType.MESSAGE_COMM_MES.equals(message.getMesType())) {
                    System.out.println("\n" + message.getSender() + "对你说：" + message.getContent() + "\t" + message.getSendTime());
                } else if (MessageType.MESSAGE_TO_ALL_MES.equals(message.getMesType())) {
                    System.out.println("\n" + message.getSender() + "对大家说：" + message.getContent() + "\t" + message.getSendTime());
                } else if (MessageType.MESSAGE_FILE_MES.equals(message.getMesType())) {
                    System.out.println("\n" + message.getSender() + "给你发送了文件");

                    // 取出message文件的字节数组，通过文件输出流写到磁盘
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(message.getDest());
                        fileOutputStream.write(message.getFileBytes());
                        System.out.println("保存文件成功");
                        fileOutputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    System.out.println("别的type");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }
}
